package com.yanqu.road.dao.impl.cross.unionwar;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.unionwar.CrossUnionGuessData;
import com.yanqu.road.utils.string.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionWarGuessDaoImpl extends TempDataObjectDao<CrossUnionGuessData> {

    @Override
    protected boolean addData(CrossUnionGuessData data) {
        PreparedStatement call = null;
        String sql = "insert into t_c_guess_data(activityId,stage,serverId,userId,unionUid,syncTime,userBaseInfo,groupId) values "
                + "(?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getStage());
            call.setLong(i++, data.getServerId());
            call.setLong(i++, data.getUserId());
            call.setString(i++, StringUtils.listToString(data.getUnionUid(), ","));
            call.setLong(i++, data.getSyncTime());
            call.setString(i++, JSONObject.toJSONString(data.getUserBaseInfo()));
            call.setInt(i++, data.getGroupId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(CrossUnionGuessData data) {
        PreparedStatement call = null;
        String sql = "update t_c_guess_data set unionUid = ?, syncTime = ?, userBaseInfo = ?, groupId = ? where activityId = ? and stage = ? and serverId = ? and userId = ?";
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, StringUtils.listToString(data.getUnionUid(), ","));
            call.setLong(i++, data.getSyncTime());
            call.setString(i++, JSONObject.toJSONString(data.getUserBaseInfo()));
            call.setInt(i++, data.getGroupId());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getStage());
            call.setLong(i++, data.getServerId());
            call.setLong(i++, data.getUserId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    //activityId - stage - groupId - userId
    public Map<Integer, Map<Integer, Map<Integer, Map<Long, CrossUnionGuessData>>>> getCrossGuessDataMap(List<Integer> activityIdList) {
        String sql = "select * from t_c_guess_data where activityId in(" + StringUtils.listToString(activityIdList, ",") + ")";
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Integer, Map<Integer, Map<Long, CrossUnionGuessData>>>> dataMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getCrossDb());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossUnionGuessData data = parse(rs);
                if (!dataMap.containsKey(data.getActivityId())) {
                    dataMap.put(data.getActivityId(), new ConcurrentHashMap<>());
                }
                if (!dataMap.get(data.getActivityId()).containsKey(data.getStage())) {
                    dataMap.get(data.getActivityId()).put(data.getStage(), new ConcurrentHashMap<>());
                }
                if (!dataMap.get(data.getActivityId()).get(data.getStage()).containsKey(data.getGroupId())) {
                    dataMap.get(data.getActivityId()).get(data.getStage()).put(data.getGroupId(), new ConcurrentHashMap<>());
                }
                dataMap.get(data.getActivityId()).get(data.getStage()).get(data.getGroupId()).put(data.getUserId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    @Override
    protected CrossUnionGuessData parseData(ResultSet rs) throws SQLException {
        CrossUnionGuessData data = new CrossUnionGuessData();
        data.setActivityId(rs.getInt("activityId"));
        data.setStage(rs.getInt("stage"));
        data.setServerId(rs.getLong("serverId"));
        data.setUserId(rs.getLong("userId"));
        data.setUnionUid(StringUtils.stringToStringList(rs.getString("unionUid"), ","));
        data.setSyncTime(rs.getLong("syncTime"));
        data.setUserBaseInfo(JSONObject.parseObject(rs.getString("userBaseInfo"), UserBaseInfo.class));
        data.setGroupId(rs.getInt("groupId"));
        return data;
    }
}
